<?php

namespace App\Services;

use App\Exceptions\AppException;
use App\Models\DataDict;
use App\Models\District;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class UserService
{
    public static function detail($value = null) {
        /**
         * @var User $user
         */
        $user = null;
        if ($value instanceof User) {
            $user = $value;
        } elseif (is_numeric($value)) {
            $user = User::where(['id'=>$value])->first();
        } elseif ($value === null) {
            $user = Auth::user();
        }
        if (empty($user)) {
            throw new AppException('参数不正确');
        }

        $result = $user->toArray();
        $result['roles'] = $user->getRoleNames()->all();
        $result['permissions'] = $user->getAllPermissions()->pluck('name')->all();
        $result['district'] = $user->district->toArray();

        return $result;
    }

    public static function checkRoleType($userDistrictId, $type) {
        if ($userDistrictId == District::CITY_ID && $type == DataDict::TYPE_DISTRICT ||
            $userDistrictId != District::CITY_ID && $type == DataDict::TYPE_CITY) {
            //市级用户不能分配区县级角色，区县级用户不能分配市级角色
            throw new AppException('用户角色不匹配');
        }

        return true;
    }
}
